package com.itee.street.excel;

import com.itee.core.util.StringCoder;
import com.itee.street.entity.Term;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ImportXlsData {

    public static List<Term> readExcel(InputStream inputStream, boolean reverse) throws Exception {
        POIFSFileSystem fs = new POIFSFileSystem(inputStream);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow row = sheet.getRow(0);
        //int colNum = row.getPhysicalNumberOfCells();
        int rowNum = sheet.getPhysicalNumberOfRows();
        List<Term> meters = new ArrayList<>();
        if (rowNum > 0) {
            for (int i = 0; i < rowNum; i++) {
                Term term = new Term();
                row = sheet.getRow(i);
                HSSFCell cell = row.getCell(0);
                String termUid = getValue(cell);
                if (StringUtils.isNotBlank(termUid)) {
                    term.setTermUid(StringCoder.fillZeroLeft(termUid, 12));
                    if (reverse) {
                        byte[] uidBcd = StringCoder.hexStringToByte(term.getTermUid());
                        ArrayUtils.reverse(uidBcd);
                        term.setTermUid(StringCoder.bytesToHexString(uidBcd));
                    }
                    HSSFCell cell1 = row.getCell(1);
                    if (cell1 != null) {
                        term.setPn(Integer.parseInt(getValue(cell1)));
                    }
                    meters.add(term);
                }

            }
        }
        inputStream.close();
        wb.close();
        return meters;
    }

    private static String getValue(HSSFCell hssfCell) {
        if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
            return String.valueOf((int) hssfCell.getNumericCellValue());
        } else if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
            return String.valueOf(hssfCell.getStringCellValue());
        } else {
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }
}
